<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta name="_csrf" th:content="${_csrf != null ? _csrf.token : ''}"/>
    <meta name="_csrf_header" th:content="${_csrf != null ? _csrf.headerName : ''}"/>
    <link rel="icon" type="image/x-icon" href="/images/favicon.ico">
    <link rel="shortcut icon" type="image/x-icon" href="/images/favicon.ico">
    <title>回收员工作台</title>
    <!-- 先加载所有CSS -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdn.jsdelivr.net/npm/boxicons@2.1.4/css/boxicons.min.css" rel="stylesheet">
    <link rel="stylesheet" href="/css/sidebar.css">
    <link rel="stylesheet" href="/css/dashboard.css">
    <style>
        .wrapper {
            display: flex;
            width: 100%;
            min-height: 100vh;
        }

        .content {
            flex: 1;
            margin-left: var(--nav-width);
            padding: 1.5rem 2rem;
            background: #f8f9fa;
            min-height: 100vh;
            width: calc(100% - var(--nav-width));
        }

        .content-header {
            margin-bottom: 1.5rem;
            padding: 0;
        }

        .content-header h4 {
            margin: 0;
            color: #002B49;
            font-weight: 600;
            font-size: 1.2rem;
        }

        .content-body {
            background: white;
            padding: 1.5rem;
            border-radius: 8px;
            box-shadow: 0 1px 3px rgba(0,0,0,0.1);
            margin: 0 auto;
            max-width: 1400px;
        }

        .loading {
            display: none;
            position: fixed;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background: rgba(255,255,255,0.8);
            z-index: 9999;
            justify-content: center;
            align-items: center;
        }

        .loading.active {
            display: flex;
        }
    </style>
</head>
<body>
    <!-- 加载动画 -->
    <div class="loading">
        <div class="spinner-border text-primary" role="status">
            <span class="visually-hidden">加载中...</span>
        </div>
    </div>

    <div class="wrapper">
        <!-- 侧边栏 -->
        <nav class="sidebar">
            <div class="sidebar-header">
                <h5 class="mb-0">回收员工作台</h5>
                <small th:text="${collector != null ? collector.realName : '回收员'}">回收员</small>
            </div>
            <div class="nav-menu">
                <div class="menu-label">工作台</div>
                <a class="nav-link active" href="#/dashboard">
                    <i class='bx bxs-dashboard'></i> 数据概览
                </a>
                
                <div class="menu-label">订单管理</div>
                <a class="nav-link" href="#/orders/pending">
                    <i class='bx bxs-bell'></i> 待处理订单
                </a>
                <a class="nav-link" href="#/orders/processing">
                    <i class='bx bxs-hourglass'></i> 进行中订单
                </a>
                <a class="nav-link" href="#/orders/completed">
                    <i class='bx bxs-check-circle'></i> 已完成订单
                </a>
                
                <div class="menu-label">系统功能</div>
                <a class="nav-link" href="#/profile">
                    <i class='bx bxs-user'></i> 个人中心
                </a>
                
                <div class="menu-label">其他</div>
                <a class="nav-link text-danger" href="/logout">
                    <i class='bx bx-log-out'></i> 退出登录
                </a>
            </div>
        </nav>
        
        <!-- 主要内容区域 -->
        <div class="content">
            <div class="content-header">
            </div>
            <div id="mainContent" class="content-body">
                <!-- 内容将通过AJAX动态加载 -->
            </div>
        </div>
    </div>

    <!-- 先加载基础库 -->
    <script src="https://cdn.jsdelivr.net/npm/jquery@3.6.0/dist/jquery.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
    <!-- 确保Chart.js在这里加载 -->
    <script src="https://cdn.jsdelivr.net/npm/chart.js@3.7.0/dist/chart.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
    
    <script>
        // 全局变量存储当前页面状态
        let currentPage = 'dashboard';
        let chartInitialized = false;
        
        // 页面标题映射
        const pageTitles = {
            'dashboard': '数据概览',
            'orders/pending': '待处理订单',
            'orders/processing': '进行中订单',
            'orders/completed': '已完成订单',
            'profile': '个人中心'
        };

        // 定义全局函数
        window.acceptOrderByData = function(button) {
            const orderId = button.getAttribute('data-order-id');
            const orderNo = button.getAttribute('data-order-no');
            acceptOrder(orderId, orderNo);
        };

        window.completeOrderByData = function(button) {
            const orderId = button.getAttribute('data-order-id');
            completeOrder(orderId);
        };

        window.completeOrder = function(orderId) {
            if (!orderId) {
                Swal.fire({
                    title: '错误',
                    text: '订单ID无效',
                    icon: 'error'
                });
                return;
            }

            // 显示完成订单的表单
            Swal.fire({
                title: '完成订单',
                html: `
                    <form id="completeOrderForm">
                        <div class="mb-3">
                            <label class="form-label">实际重量（kg）</label>
                            <input type="number" class="form-control" id="actualWeight" required min="0" step="0.1">
                        </div>
                        <div class="mb-3">
                            <label class="form-label">回收价格（元）</label>
                            <input type="number" class="form-control" id="price" required min="0" step="0.1">
                        </div>
                    </form>
                `,
                showCancelButton: true,
                confirmButtonText: '确认完成',
                cancelButtonText: '取消',
                preConfirm: () => {
                    const actualWeight = document.getElementById('actualWeight').value;
                    const price = document.getElementById('price').value;
                    if (!actualWeight || !price) {
                        Swal.showValidationMessage('请填写完整信息');
                        return false;
                    }
                    return { actualWeight, price };
                }
            }).then((result) => {
                if (result.isConfirmed) {
                    const { actualWeight, price } = result.value;
                    
                    // 显示加载状态
                    Swal.fire({
                        title: '处理中...',
                        text: '正在提交完成请求',
                        allowOutsideClick: false,
                        allowEscapeKey: false,
                        allowEnterKey: false,
                        showConfirmButton: false,
                        didOpen: () => {
                            Swal.showLoading();
                        }
                    });

                    // 获取CSRF令牌
                    const csrfToken = document.querySelector('meta[name="_csrf"]').getAttribute('content');
                    const csrfHeader = document.querySelector('meta[name="_csrf_header"]').getAttribute('content');

                    // 发送完成订单请求
                    fetch(`/collector/orders/complete/${orderId}`, {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/json',
                            [csrfHeader]: csrfToken
                        },
                        body: JSON.stringify({ actualWeight, price }),
                        credentials: 'same-origin'
                    })
                    .then(response => response.json())
                    .then(result => {
                        if (result.code === 200) {
                            Swal.fire({
                                title: '成功',
                                text: '订单已完成',
                                icon: 'success'
                            }).then(() => {
                                // 刷新页面
                                loadContent('orders/processing');
                            });
                        } else {
                            throw new Error(result.message || '完成订单失败');
                        }
                    })
                    .catch(error => {
                        console.error('完成订单请求失败:', error);
                        Swal.fire({
                            title: '错误',
                            text: error.message || '完成订单失败，请稍后重试',
                            icon: 'error'
                        });
                    });
                }
            });
        };

        window.navigateToOrderByData = function(button) {
            const lat = button.getAttribute('data-lat');
            const lng = button.getAttribute('data-lng');
            const address = button.getAttribute('data-address');
            
            if (!lat || !lng || !address) {
                Swal.fire({
                    title: '错误',
                    text: '地址信息不完整',
                    icon: 'error'
                });
                return;
            }

            // 使用高德地图导航
            const url = `https://uri.amap.com/navigation?to=${lng},${lat},${encodeURIComponent(address)}&mode=car&policy=1&src=myapp&callnative=0`;
            window.open(url, '_blank');
        };

        window.acceptOrder = function(orderId, orderNo) {
            if (!orderId) {
                Swal.fire({
                    title: '错误',
                    text: '订单ID无效',
                    icon: 'error'
                });
                return;
            }

            Swal.fire({
                title: '确认接单',
                text: `是否确认接单 ${orderNo}？`,
                icon: 'question',
                showCancelButton: true,
                confirmButtonText: '确认',
                cancelButtonText: '取消'
            }).then((result) => {
                if (result.isConfirmed) {
                    // 显示加载状态
                    Swal.fire({
                        title: '处理中...',
                        text: '正在处理您的接单请求',
                        allowOutsideClick: false,
                        allowEscapeKey: false,
                        allowEnterKey: false,
                        showConfirmButton: false,
                        didOpen: () => {
                            Swal.showLoading();
                        }
                    });

                    // 获取CSRF令牌
                    const csrfToken = document.querySelector('meta[name="_csrf"]').getAttribute('content');
                    const csrfHeader = document.querySelector('meta[name="_csrf_header"]').getAttribute('content');

                    // 发送接单请求
                    fetch(`/collector/orders/accept/${orderId}`, {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/json',
                            [csrfHeader]: csrfToken
                        },
                        credentials: 'same-origin'
                    })
                    .then(response => {
                        if (!response.ok) {
                            return response.text().then(text => {
                                throw new Error(text || '接单失败');
                            });
                        }
                        return response.text();
                    })
                    .then(() => {
                        Swal.fire({
                            title: '成功',
                            text: '接单成功',
                            icon: 'success'
                        }).then(() => {
                            // 刷新页面
                            loadContent('orders/pending');
                        });
                    })
                    .catch(error => {
                        console.error('接单请求失败:', error);
                        Swal.fire({
                            title: '错误',
                            text: error.message || '接单失败，请稍后重试',
                            icon: 'error'
                        });
                    });
                }
            });
        };

        window.refreshOrders = function() {
            loadContent('orders/pending');
        };

        // 全局定义图表初始化函数
        window.initOrderTrendChart = function() {
            console.log('开始初始化订单趋势图表');
            const canvas = document.getElementById('orderTrendChart');
            const chartLoading = document.querySelector('.chart-loading');
            const chartError = document.querySelector('.chart-error');
            
            if (!canvas) {
                console.error('找不到canvas元素');
                return;
            }
            
            // 显示加载状态
            if (chartLoading) chartLoading.style.display = 'block';
            if (chartError) chartError.style.display = 'none';
            
            try {
                // 验证数据
                const chartData = window.orderTrendData;
                console.log('验证图表数据:', chartData);
                
                if (!chartData) {
                    throw new Error('订单数据未定义');
                }
                
                if (!Array.isArray(chartData)) {
                    throw new Error('订单数据不是数组格式');
                }
                
                if (chartData.length === 0) {
                    throw new Error('暂无订单数据');
                }
                
                // 验证数据格式
                const isValidData = chartData.every(item => 
                    item && typeof item === 'object' && 
                    'date' in item && 'count' in item &&
                    typeof item.date === 'string' &&
                    !isNaN(parseInt(item.count))
                );
                
                if (!isValidData) {
                    throw new Error('订单数据格式不正确');
                }
                
                // 销毁已存在的图表实例
                if (window.orderChart) {
                    window.orderChart.destroy();
                }
                
                // 创建新图表
                window.orderChart = new Chart(canvas, {
                    type: 'line',
                    data: {
                        labels: chartData.map(item => {
                            const date = item.date.split('-');
                            return `${date[1]}-${date[2]}`;
                        }),
                        datasets: [{
                            label: '订单数量',
                            data: chartData.map(item => parseInt(item.count)),
                            fill: true,
                            borderColor: '#1890ff',
                            backgroundColor: 'rgba(24, 144, 255, 0.1)',
                            tension: 0.4,
                            pointRadius: 4,
                            pointBackgroundColor: '#1890ff',
                            borderWidth: 2
                        }]
                    },
                    options: {
                        responsive: true,
                        maintainAspectRatio: false,
                        animation: {
                            duration: 1000
                        },
                        layout: {
                            padding: {
                                top: 10,
                                right: 20,
                                bottom: 10,
                                left: 10
                            }
                        },
                        plugins: {
                            legend: {
                                display: false
                            },
                            tooltip: {
                                mode: 'index',
                                intersect: false,
                                backgroundColor: 'rgba(255, 255, 255, 0.9)',
                                titleColor: '#333',
                                bodyColor: '#666',
                                borderColor: '#e1e1e1',
                                borderWidth: 1,
                                padding: 10,
                                callbacks: {
                                    title: function(tooltipItems) {
                                        return '日期: ' + chartData[tooltipItems[0].dataIndex].date;
                                    },
                                    label: function(context) {
                                        return '订单数: ' + context.raw;
                                    }
                                }
                            }
                        },
                        scales: {
                            y: {
                                beginAtZero: true,
                                ticks: {
                                    stepSize: 1,
                                    color: '#666',
                                    font: {
                                        size: 12
                                    }
                                },
                                grid: {
                                    color: '#f0f0f0',
                                    drawBorder: false
                                }
                            },
                            x: {
                                grid: {
                                    display: false
                                },
                                ticks: {
                                    color: '#666',
                                    font: {
                                        size: 12
                                    }
                                }
                            }
                        }
                    }
                });
                
                console.log('图表创建成功');
                chartInitialized = true;
                if (chartLoading) chartLoading.style.display = 'none';
                
            } catch (error) {
                console.error('图表初始化失败:', error);
                if (chartLoading) chartLoading.style.display = 'none';
                if (chartError) {
                    chartError.style.display = 'block';
                    chartError.textContent = '图表加载失败: ' + error.message;
                }
            }
        };

        // 加载内容
        function loadContent(page) {
            console.log('开始加载页面:', page);
            const loading = document.querySelector('.loading');
            loading.classList.add('active');
            
            // 更新导航状态
            document.querySelectorAll('.nav-link').forEach(link => {
                link.classList.remove('active');
                if (link.getAttribute('href') === '#/' + page) {
                    link.classList.add('active');
                }
            });
            
            // 加载页面内容
            fetch('/collector/' + page)
                .then(response => {
                    if (!response.ok) {
                        throw new Error('页面加载失败');
                    }
                    console.log('页面请求成功');
                    return response.text();
                })
                .then(html => {
                    console.log('获取到页面内容');
                    const mainContent = document.getElementById('mainContent');
                    mainContent.innerHTML = html;
                    
                    // 如果是仪表盘页面，等待内容加载完成后初始化图表
                    if (page === 'dashboard') {
                        console.log('当前是仪表盘页面');
                        currentPage = 'dashboard';
                        
                        // 检查调试数据
                        const debugData = document.getElementById('debug-data');
                        if (debugData) {
                            console.log('调试数据内容:', debugData.textContent);
                            // 等待DOM更新完成后初始化图表
                            setTimeout(() => {
                                const canvas = document.getElementById('orderTrendChart');
                                if (canvas) {
                                    console.log('找到canvas元素，开始渲染图表');
                                    // 确保之前的图表实例被销毁
                                    const existingChart = Chart.getChart(canvas);
                                    if (existingChart) {
                                        existingChart.destroy();
                                    }
                                    // 触发图表初始化
                                    const chartScript = document.querySelector('script[data-chart-init]');
                                    if (chartScript) {
                                        eval(chartScript.textContent);
                                    }
                                } else {
                                    console.error('未找到canvas元素');
                                }
                            }, 100);
                        }
                    }
                })
                .catch(error => {
                    console.error('加载页面失败:', error);
                    Swal.fire({
                        title: '错误',
                        text: error.message,
                        icon: 'error'
                    });
                })
                .finally(() => {
                    loading.classList.remove('active');
                });
        }

        // 页面加载完成后加载默认内容
        document.addEventListener('DOMContentLoaded', function() {
            // 处理导航链接点击
            document.querySelectorAll('.nav-link').forEach(link => {
                link.addEventListener('click', (e) => {
                    if (!link.getAttribute('href').startsWith('#/')) return;
                    e.preventDefault();
                    const page = link.getAttribute('href').substring(2);
                    loadContent(page);
                });
            });
            
            // 加载默认页面
            loadContent('dashboard');
        });

        // 监听窗口大小变化
        window.addEventListener('resize', function() {
            if (currentPage === 'dashboard') {
                const canvas = document.getElementById('orderTrendChart');
                if (canvas) {
                    const chart = Chart.getChart(canvas);
                    if (chart) {
                        chart.resize();
                    }
                }
            }
        });
    </script>
</body>
</html> 